package com.xiaxiang.ar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.dg.acb.utils.configdata.DGConfigData;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
import com.xiaxiang.ar.ARCloud.ARCloudEditor;
import com.xiaxiang.ar.xml.VideoXmlData;
import com.xiaxiang.ar.xml.XmlSerializerBuilder;
import com.xiaxiang.xiaxwan.ar.data.ConfigDataTool;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UnityActivity extends UnityPlayerActivity {
    private LinearLayout mLlUnityContainer;
    private Button mBtnRecord;
    private Button mBtnARClose;
    private Button mBtnARChangeCamera;
    private Button mBtnPreview;
    private boolean isRecording = false;
    private String u3dModelName = "default.unity3d";
    private String u3dModelFullPath;
    private ImageView bgView = null;
    private FrameLayout mARCtlView = null;
    private final static String MATERIAL_NAME_KEY = "materialName";
    private final static String TARGET_NAME_KEY = "targetName";
    private final static String MATERIAL_ID_KEY = "materialId";
    private final static String MATERIAL_URL_KEY = "materialUrl";
    private final static String USER_NAME_KEY = "userName";
    private final static String NAME_KEY = "name";
    private String mUserName = "";
    private String mName = "";
    private int mMaterialId = 0;
    private String mMaterialUrl ="";
    private int mCurrentARMode = 0;
    private String mCurrentARVideo = "";
    private XXARMaterialVideoData mMaterialData;
    private DGConfigData mConfigData;
    private String easyARKey  = "";
    public final static String MATERIAL_VIDEO_DATA_KEY = "arMaterialVideoData";
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_unity);
        mConfigData = new DGConfigData(this);
        ARCloudEditor.GetKey(this, new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                Log.i("drj", "key:" + result.result);
                easyARKey = result.result;
            }

            @Override
            public void onError(String error) {
                Log.i("drj", "key:" + error);
            }
        });
        Intent intent = getIntent();
        if(intent != null){
            mCurrentARMode = intent.getIntExtra("arMode", 0);
            Log.d("UnityActivity", "onCreate:mCurrentARMode="+mCurrentARMode);
            if (mCurrentARMode == 1) {
                mMaterialData = intent.getParcelableExtra(ConfigDataTool.MATERIAL_VIDEO_DATA_KEY);
                if(mMaterialData != null){
                    u3dModelName = mMaterialData.mMaterialPathName;
                    u3dModelFullPath = "file://" + u3dModelName;
                }
            }
        }
        initView();
        initUnity3d();
    }

    @Override
    protected void onPause() {
        UnityPlayer.UnitySendMessage("EasyAR_Startup", "onARCameraPause", "unused");
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        if(intent != null){
            mCurrentARMode = intent.getIntExtra("arMode", 0);
            Log.d("UnityActivity", "onNewIntent:mCurrentARMode="+mCurrentARMode);
            if (mCurrentARMode == 1) {
                mMaterialData = intent.getParcelableExtra(ConfigDataTool.MATERIAL_VIDEO_DATA_KEY);
                if(mMaterialData != null){
                    u3dModelName = mMaterialData.mMaterialPathName;
                    u3dModelFullPath = "file://" + u3dModelName;
                }
            }
        }
        initUnity3d();
    }

    public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            moveTaskToBack(true);
        }
        return true;
    }

    private void setCurrentARMode() {
        if (mCurrentARMode == 1) {
            UnityPlayer.UnitySendMessage("RenderCamera", "EnableCameraTrack", "unused");
        } else {
            UnityPlayer.UnitySendMessage("RenderCamera", "DisableCameraTrack", "unused");
        }
    }

    private void setCurrentARModel()
    {
        if (!TextUtils.isEmpty(u3dModelFullPath) ) {
            UnityPlayer.UnitySendMessage("EasyAR_Startup", "SetCurrentModel", u3dModelFullPath);
        }
    }

    public static String getDefaultVideoPath(String pkName){
        String sdcard = getSdcardPath();
        String videoPath = sdcard + pkName + "/video/";
        return videoPath;
    }

    private void initUnity3d() {
        setCurrentARModel();
        setCurrentARMode();
    }

    private void  startSplash() {
        mARCtlView.setVisibility(View.GONE);
        bgView = new ImageView(this);
        bgView.setScaleType(ImageView.ScaleType.FIT_XY);
        bgView.setBackgroundColor(0);
        Glide.with(UnityActivity.this).load(R.drawable.unity_splash).into(bgView);
        mUnityPlayer.addView(bgView);
    }

    private void stopSplash() {
        if (bgView != null) {
            mUnityPlayer.removeView(bgView);
            mARCtlView.setVisibility(View.VISIBLE);
        }

        initUnity3d();
    }

    public void u3dCallStopSplash(final String unused) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                stopSplash();
            }
        });
    }

    public String u3dCallGetEasyARKey() {
        return easyARKey;
    }

    public String u3dCallGetCurrentVideoPath() {
        return getDefaultVideoPath(this.getPackageName());
    }

    private void initView() {
        mLlUnityContainer = (LinearLayout) findViewById(R.id.ll_unity_container);
        mBtnRecord = (Button) findViewById(R.id.btn_record);
        mBtnARClose = (Button) findViewById(R.id.btn_ar_close);
        mBtnARChangeCamera = (Button) findViewById(R.id.btn_change_camera);
        mBtnPreview = (Button)findViewById(R.id.btn_preview);
        mARCtlView = (FrameLayout)findViewById(R.id.ar_ctl_view);

        //将Unity的View添加到布局里
        startSplash();
        View scene = mUnityPlayer.getView();
        mLlUnityContainer.addView(scene);

        mBtnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //向Unity的EasyAR_Startup对象上的脚本里的RecordVideoOp方法发送消息
                //第三个参数是传递的消息
                if (isRecording) {
                    UnityPlayer.UnitySendMessage("EasyAR_Startup", "RecordVideoOp", "0");
                    isRecording = false;
                    mBtnRecord.setBackgroundResource(R.drawable.cp_start);
                } else {
                    UnityPlayer.UnitySendMessage("EasyAR_Startup", "RecordVideoOp", "1");
                    isRecording = true;
                    mBtnRecord.setBackgroundResource(R.drawable.cp_stop);
                }
            }
        });

        mBtnARChangeCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UnityPlayer.UnitySendMessage("EasyAR_Startup", "ChangeCamera", "unused");
            }
        });

        mBtnARClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moveTaskToBack(true);
            }
        });

        mBtnPreview.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.xiaxiang.xiawan.video.preview");
                intent.setPackage(getPackageName());
                if(mMaterialData != null){
                    mMaterialData.mVideoPath = mCurrentARVideo;
                    intent.putExtra(ConfigDataTool.MATERIAL_VIDEO_DATA_KEY,mMaterialData);
                }else{
                    mMaterialData = new XXARMaterialVideoData();
                }
                startActivity(intent);
                /*
                VideoXmlData videoXmlData  = new VideoXmlData();
                videoXmlData.mMaterialId = mMaterialData.mMaterialId;
                videoXmlData.mMaterialUrl = mMaterialData.mMaterialUrl;
                XmlFileCreator(getSdcardPath()+"aa.xml",videoXmlData);
                */
            }
        });
    }

    private void u3dCallRecordSuccess(String video){
        mCurrentARVideo = video;
        Log.i("xxx", "u3dCallRecordSuccess:" + video);
        if(mMaterialData != null){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put(XXARMaterialVideoData.MATERIAL_ID_KEY,mMaterialData.mMaterialId);
                jsonObject.put(XXARMaterialVideoData.MATERIAL_URL_KEY,mMaterialData.mMaterialUrl);
               // jsonObject.put(XXARMaterialVideoData.NAME_KEY,mMaterialData.mName);
               // jsonObject.put(XXARMaterialVideoData.USER_NAME_KEY,mMaterialData.mUserName);
                mConfigData.insertConf(mCurrentARVideo,jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getSdcardPath(){
        String path = "/mnt/emmc/";
        File file = new File(path);
        if(file.exists()){
            return path;
        }
        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            path =  Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
        }
        else
        {
            path = "/sdcard/";
        }
        return path;
    }

    private static void XmlFileCreator(String xmlPath,VideoXmlData xmlData) {
        XmlSerializerBuilder xmlSerializerBuilder = new XmlSerializerBuilder(xmlPath,VideoXmlData.HOME_TAG);
        xmlSerializerBuilder.startSerializer();
        xmlSerializerBuilder.writeTag(VideoXmlData.MATERIAL_ID_KEY,xmlData.mMaterialId);
        xmlSerializerBuilder.writeTag(VideoXmlData.MATERIAL_URL_KEY,xmlData.mMaterialUrl);
        xmlSerializerBuilder.finishSerializer();
    }
}
